package com.yootk;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

public class YootkDemo9 {
    public static void main(String[] args) throws Exception {
        final int repeat = 5;
        Exchanger<String> exc = new Exchanger<>();

        new Thread(() -> {
            for (int x = 0; x < repeat; x++) {
                try {
                    String info = "www.yootk.com - " + x;
                    exc.exchange(info); // 数据存储
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "信息生产者").start();

        new Thread(() -> {
            for (int y = 0; y < repeat; y++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    String info = exc.exchange(null);
                    System.out.println("[" + Thread.currentThread().getName() + "] " + info);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "信息消费者").start();
    }
}
